package com.api.gbhg.luoao.web;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.*;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.word.TableUtil;
import com.api.gbhg.luoao.la.dao.BudgetModifyDao;
import com.api.gbhg.luoao.la.util.DaoUtil;
import com.ibm.icu.text.SimpleDateFormat;
import org.apache.commons.lang.StringUtils;
import org.docx4j.wml.U;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.Util;

import static com.api.gbhg.lbj.tool.Tools.*;

import com.api.gbhg.luoao.la.util.R;

/**
 * @author
 * @Title:
 * @Package
 * @Description:
 * @date 2022/7/2610:00
 */
@Path("/gbhg/SpendingChannel")
public class SpendingChannelAdjustTheApi {
    public static BaseBean baseBean = new BaseBean();

    /**
     * 支出渠道调整
     */
    @POST
    @Path("/AdjustThe")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String GetSpendingChannelAdjustThe(Map<String, Object> params) {

        Map<String, Object> leftObject;
        if (params.containsKey("leftObject")) {
            leftObject = (Map<String, Object>) params.get("leftObject");
        } else {
            return JSONUtil.toJsonStr(R.error().message("左侧集合存在！"));
        }

        Map<String, Object> rightObject;
        if (params.containsKey("rightObject")) {
            rightObject = (Map<String, Object>) params.get("rightObject");
        } else {
            return JSONUtil.toJsonStr(R.error().message("右侧集合存在！"));
        }
        String leftProjectId = Util.null2String(leftObject.get("ProjectId")); // 左侧项目id
        String rightProjectId = Util.null2String(rightObject.get("ProjectId")); // 右侧项目id
        if (leftProjectId.equals(rightProjectId)) {
            return JSONUtil.toJsonStr(R.error().message("相同项目不能进行调整！"));
        }

        RecordSetTrans recordSetTrans = new RecordSetTrans();
        recordSetTrans.setAutoCommit(false);


        String requestid = Util.null2String(params.get("requestid")); // 流程id
        String userID = Util.null2String(params.get("userID"));// 当前登录人
        String mainId = "";
        try {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = formatter.format(calendar.getTime());
            boolean jude = false;
            jude = recordSetTrans.executeUpdate("insert into uf_zcqdtzjl(requestId,dzr,dzsj,mbxm1,mbxm2) VALUES(?,?,?,?,?)", requestid, userID
                    , format, leftProjectId, rightProjectId);
            if(!jude){
                recordSetTrans.rollback();
                return JSONUtil.toJsonStr(R.error().message("日志记录新增失败！"));
            }
            Map<String, Object> mapBySql = DaoUtil.getMapBySql("select id from uf_zcqdtzjl where dzr =? and dzsj = ? and mbxm1 =? and mbxm2 = ? ", userID
                    , format, leftProjectId, rightProjectId);
            if(mapBySql!=null && mapBySql.size()>0){
                mainId = Util.null2String(mapBySql.get("id"));
            }else{
                recordSetTrans.rollback();
                return JSONUtil.toJsonStr(R.error().message("日志表中查无主表数据！"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        // 左边渠道进行数据查询是否存在
        String leftSql = "select count(id) as cut from uf_jingfeilaiyuan where lcid= " + leftProjectId;
        List<Map<String, Object>> leftList = (List<Map<String, Object>>) leftObject.get("leftList");
        R leftR = judeDataisThereAre(recordSetTrans, leftSql, leftList);
        if (leftR.getCode() == 500) {
            recordSetTrans.rollback();
            return JSONUtil.toJsonStr(leftR);
        }


        // 右边渠道进行数据查询是否存在
        String rightSql = "select count(id) as cut from uf_jingfeilaiyuan where lcid= " + rightProjectId;
        List<Map<String, Object>> rightList = (List<Map<String, Object>>) rightObject.get("rightList");
        R rightR = judeDataisThereAre(recordSetTrans, rightSql, rightList);
        if (rightR.getCode() == 500) {
            recordSetTrans.rollback();
            return JSONUtil.toJsonStr(rightR);
        }

        // 左边渠道调整至右边渠道
        String left_rightSql = "select id,syed,je from uf_jingfeilaiyuan where lcid= " + rightProjectId;
        R left_tightJude = updateAndInsertData(recordSetTrans, left_rightSql, leftObject, rightProjectId, "0",mainId);
        if (left_tightJude.getCode() == 500) {
            recordSetTrans.rollback();
            return JSONUtil.toJsonStr(left_tightJude);
        }

        // 右边渠道调整至左边渠道
        String right_leftSql = "select id,syed,je from uf_jingfeilaiyuan where lcid= " + leftProjectId;
        R right_leftJude = updateAndInsertData(recordSetTrans, right_leftSql, rightObject, leftProjectId, "1",mainId);
        if (right_leftJude.getCode() == 500) {
            recordSetTrans.rollback();
            return JSONUtil.toJsonStr(right_leftJude);
        }

        recordSetTrans.commit();
        return JSONUtil.toJsonStr(R.ok());
    }


    // 用于判断是否集合中数据是否存在数据库中
    public R judeDataisThereAre(RecordSetTrans recordSetTrans, String sql, List<Map<String, Object>> list) {
        StringBuilder sb = new StringBuilder();
        int number = 0;
        if (list != null && list.size() > 0) {
            for (Map<String, Object> itme : list) {
                number++;
                sb.append(sql);
                if (itme.get("lylx").equals("0")) {
                    sb.append(" and yslylx = '当年预算核批' ");
                } else {
                    sb.append(" and yslylx = '上年结转核批' ");
                }

                if (itme.get("srlx").equals("1")) {
                    sb.append(" and srlx = 1 ");
                    String zcqd = Util.null2String(itme.get("zcqd"));
                    if (zcqd.equals("5") || zcqd.equals("8")) {
                        sb.append(" and zcqd = " + zcqd + " and dfczbkxm = " + Util.null2String(itme.get("dfczbkxm")));
                    } else {
                        sb.append(" and zcqd = " + zcqd);
                    }
                } else {
                    sb.append(" ·and srlx = 0 and zyczbksr = '" + Util.null2String(itme.get("zyczbksr")) + "'");
                }
                try {
                    recordSetTrans.executeQuery(sb.toString());
                    recordSetTrans.next();
                    String cut = recordSetTrans.getString("cut");
                    if (Integer.valueOf(cut) <= 0) {
                        return R.error().message("左侧支出渠道第" + number + "条不存在与数据库中！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return R.ok();
        } else {
            return R.error().message("进入判断时集合为空！");
        }
    }


    // 修改或插入一条数据
    public R updateAndInsertData(RecordSetTrans recordSetTrans, String sql, Map<String, Object> leftObject, String lcjlsqjlid, String leftOrRight,String mainId) {
        StringBuilder sb = new StringBuilder();
        List<Map<String, Object>> list = null;
        StringBuilder sbdt = new StringBuilder();
        if (leftOrRight.equals("0")) {
            list = (List<Map<String, Object>>) leftObject.get("leftList");
            //左边的调整内容插入明细1，右边的插入明细2
            sbdt.append("insert into uf_zcqdtzjl_dt2(mainid,lylx,srlx,zcqd,dfczbkxm,zyczbksr,dzje) VALUES(?,?,?,?,?,?,?)");
        } else {
            list = (List<Map<String, Object>>) leftObject.get("rightList");
            sbdt.append("insert into uf_zcqdtzjl_dt1(mainid,lylx,srlx,zcqd,dfczbkxm,zyczbksr,dzje) VALUES(?,?,?,?,?,?,?)");
        }
        List<Object> paramsSql = new ArrayList<>();
        paramsSql.add(mainId);
        if (list != null && list.size() > 0) {

            for (Map<String, Object> itme : list) {
                sb.append(sql);
                if (itme.get("lylx").equals("0")) {
                    sb.append(" and yslylx = '当年预算核批' ");
                    paramsSql.add("当年预算核批");
                } else {
                    sb.append(" and yslylx = '上年结转核批' ");
                    paramsSql.add("上年结转核批");
                }

                if (itme.get("srlx").equals("1")) {
                    sb.append(" and srlx = 1 ");
                    String zcqd = Util.null2String(itme.get("zcqd"));
                    if (zcqd.equals("5") || zcqd.equals("8")) {
                        sb.append(" and zcqd = " + zcqd + " and dfczbkxm = " + Util.null2String(itme.get("dfczbkxm")));
                    } else {
                        sb.append(" and zcqd = " + zcqd);
                    }
                } else {
                    sb.append(" and srlx = 0 and zyczbksr = '" + Util.null2String(itme.get("zyczbksr")) + "'");
                }
                try {
                    Map<String, Object> mapBySql = DaoUtil.getMapBySql(sb.toString());
                    if (mapBySql != null && mapBySql.size() > 0) {
                        String hpje = Util.null2String(itme.get("hpje")); // 调剂额度
                        boolean jude = recordSetTrans.executeUpdate("update uf_jingfeilaiyuan set syed = ?,je =?  where id = ? "
                                , BudgetModifyDao.add(hpje, Util.null2String(mapBySql.get("syed"))).toString()
                                , BudgetModifyDao.add(hpje, Util.null2String(mapBySql.get("je"))).toString()
                                , Util.null2String(mapBySql.get("id")));
                        if (!jude) {
                            recordSetTrans.rollback();
                            return R.error().message("修改" + (leftOrRight.equals("0") ? "右侧的数据失败" : "左侧的数据失败"));
                        }
                    } else {
                        String srlx = Util.null2String(itme.get("srlx")); // 收入类型
                        String YJ = baseBean.getPropValue("Verification", "yj");
                        String XJ = baseBean.getPropValue("Verification", "xj");
                        String sbdw = Util.null2String(leftObject.get("sbdw")); // 申报单位
                        String ysnd = Util.null2String(leftObject.get("ysnd")); // 预算年度
                        Calendar calendar = Calendar.getInstance();
                        int year = calendar.get(Calendar.YEAR);//当前年份
                        int year1 = calendar.get(Calendar.YEAR);//上年年份

                        int sum1 = 0;
                        int sum2 = 0;
                        List<Object> listParams = new ArrayList<>();
                        //支出渠道
                        String zcqd = Util.null2String(itme.get("zcqd"));
                        //功能科目_新
                        String gnkm = "";
                        //中央财政拨款项目
                        String zyczbksr = Util.null2String(itme.get("zyczbksr"));
                        //地方财政拨款项目
                        String dfczbkxm = Util.null2String(itme.get("dfczbkxm"));
                        if (srlx.equals("0")) {//0：中央
                            if (StringUtils.isNotBlank(zyczbksr)) {
                                String[] sta = zyczbksr.split("_");//当年结转核批下划线分割
                                sum1 = Integer.parseInt(sta[0]);//9为科目级，10为科目下级
                                sum2 = Integer.parseInt(sta[1]);//表id
                                if (sum1 == Integer.parseInt(YJ)) {
                                    gnkm = getSubjectsGnkm(sum2);
                                } else if (sum1 == Integer.parseInt(XJ)) {
                                    gnkm = getSubjectsGnkm(getSubjectsGnkm2(sum2));
                                }
                            }
                        }
                        if (srlx.equals("1")) {//1:非中央
                            RecordSet rs1 = theCentral(zcqd, itme.get("lylx").equals("0") ? year : year1, sbdw);
                            rs1.next();
                            gnkm = rs1.getString("gnkm");
                        }
                        //核批金额
                        String hpje = Util.null2String(itme.get("hpje"));//核批来源明细预算减少金额
                        listParams.add(sbdw); // 上报单位
                        listParams.add(ysnd); // 预算年度
                        listParams.add(zcqd); // 来源类型
                        listParams.add(gnkm); // 功能科目
                        listParams.add(hpje); // 金额
                        listParams.add(hpje); // 剩余额度
                        listParams.add(0); // 冻结金额
                        listParams.add(itme.get("lylx").equals("0") ? "当年预算核批" : "上年结转核批"); // 预算来源类型
                        listParams.add(srlx); // 收入类型
                        listParams.add(dfczbkxm); // 地方财政拨款项目上年结转
                        listParams.add(zyczbksr); // 中央财政拨款收入
                        listParams.add(lcjlsqjlid);
                        String sqlINSERT = "INSERT into uf_jingfeilaiyuan(sbdw,nd,zcqd,gnkm,je,syed,djje,yslylx,srlx,dfczbkxm,zyczbksr,lcid)\n" +
                                "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
                        boolean jude = recordSetTrans.executeUpdate(sqlINSERT, listParams);
                        if (!jude) {
                            recordSetTrans.rollback();
                            return R.error().message("新增" + (leftOrRight.equals("0") ? "右侧的数据失败" : "左侧的数据失败"));
                        }
                    }

                    paramsSql.add(Util.null2String(itme.get("srlx")));
                    paramsSql.add(Util.null2String(itme.get("zcqd")));
                    paramsSql.add(Util.null2String(itme.get("dfczbkxm")));
                    paramsSql.add(Util.null2String(itme.get("zyczbksr")));
                    paramsSql.add(Util.null2String(itme.get("hpje")));
                    boolean jude = recordSetTrans.executeUpdate(sbdt.toString(), paramsSql);
                    if(!jude){
                        recordSetTrans.rollback();
                        return R.error().message("新增" + (leftOrRight.equals("0") ? "右侧的日志记录失败" : "左侧的日志记录失败"));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return R.ok();
        }else{
            return R.error().message("执行修改及新增数据时集合为空");
        }

    }
}
